#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Author:Lijiacai
Email:1050518702@qq.com
===========================================
CopyRight@JackLee.com
===========================================
"""
import logging
import os
import sys
import json
import requests
import multiprocessing

cur_dir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append("%s/.." % cur_dir)
import config

sys.path.append("%s/.." % cur_dir)
from res.lijiacai.utils import tool


def baidu_api(origins, destinations, baidu_ak, city, start_id, end_id, out):
    url = f"http://api.map.baidu.com/routematrix/v2/driving?output=json&origins={origins}&destinations={destinations}&ak={baidu_ak}"
    res = requests.get(url=url).json()
    if res.get("result", []):
        out[f"{city}_{start_id}_{end_id}"] = res.get("result", [])[0].get("distance", {}).get(
            "value")
    else:
        logging.debug(res)


class StationDistance():
    baidu_ak = "eqlcRflrG2vqoncNzlfjbiUqGq3FL6w7"
    station_key = "d9c227c0-a4d2-40ba-b51b-4e479431708a"

    def __init__(self):
        self.redis_client = tool.RedisDB(**config.redis_conf).client

    def getStations(self):
        headers = {
            "accessKey": self.station_key
        }
        cityIds = [400000, 610000, 650000]
        out = {}
        for city in cityIds:
            mid = {}
            res = requests.get(
                f"http://admin.pand-auto.com/Admin/order/person/getStationsByCitycode.do?condition.cityId={city}",
                headers=headers).json()
            datetimeStr = res.get("cityStations").get("datetimeStr")
            for one in res.get("cityStations").get("stations"):
                allNum = one.get("allNum", 0)
                areaId = one.get("areaId", 0)
                changeNum = one.get("changeNum", 0)
                chargingNum = one.get("chargingNum", 0)
                freeNum = one.get("freeNum", 0)
                latitude = one.get("latitude", 0)
                longitude = one.get("longitude", 0)
                overNum = one.get("overNum", 0)
                parkingNum = one.get("parkingNum", 0)
                stationId = one.get("stationId", 0)
                stationName = one.get("stationName", "")
                vehicleInfos = one.get("vehicleInfos", [])
                mid[stationId] = {"stationName": stationName,
                                  "latitude": latitude,
                                  "longitude": longitude,
                                  "stationId": stationId}
            out[city] = mid
        return out

    def run(self):
        res = self.getStations()
        locations = {}
        for city, v in res.items():
            station_id_list = []
            station_location = []
            for station_id, info in v.items():
                station_id_list.append(station_id)
                station_location.append(f'{info.get("latitude")},{info.get("longitude")}')
            locations[city] = [station_id_list, station_location]
        for city, v in locations.items():
            station_ids = v[0]
            station_locations = v[1]
            out = {}
            length = len(station_ids)
            for i in range(length):
                for j in range(length):
                    if i == j:
                        continue

                    origins = station_locations[i]
                    destinations = station_locations[j]
                    url = f"http://api.map.baidu.com/routematrix/v2/driving?output=json&origins={origins}&destinations={destinations}&ak={self.baidu_ak}"
                    res = requests.get(url=url).json()
                    if res.get("result", []):
                        out[f"{station_ids[i]}_{station_ids[j]}"] = res.get("result", [])[0].get("distance", {}).get(
                            "value")
                    else:
                        logging.debug(res)
            key = f"station_distance_{city}"
            try:
                self.redis_client.set(key, json.dumps(out), ex=None, px=None, nx=False, xx=False)
            except Exception as e:
                logging.exception(str(e))

    def run_(self):
        pool = multiprocessing.Pool(10)
        out = multiprocessing.Manager().dict()
        res = self.getStations()
        locations = {}
        for city, v in res.items():
            station_id_list = []
            station_location = []
            for station_id, info in v.items():
                station_id_list.append(station_id)
                station_location.append(f'{info.get("latitude")},{info.get("longitude")}')
            locations[city] = [station_id_list, station_location]
        for city, v in locations.items():
            station_ids = v[0]
            station_locations = v[1]
            length = len(station_ids)
            for i in range(length):
                for j in range(length):
                    if i == j:
                        continue

                    origins = station_locations[i]
                    destinations = station_locations[j]
                    pool.apply_async(baidu_api, args=(
                        origins, destinations, self.baidu_ak, city, station_ids[i], station_ids[j], out))
        pool.close()
        pool.join()
        key = f"station_distance"
        try:
            self.redis_client.set(key, json.dumps(dict(out)), ex=None, px=None, nx=False, xx=False)
        except Exception as e:
            logging.exception(str(e))

    def go(self):
        res = self.run_()


if __name__ == '__main__':
    StationDistance().go()
